package org.opsli.modulars.business.iot.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import org.opsli.modulars.business.app.web.ZkUtils;
import org.opsli.modulars.business.iot.protocol.ConvertCode;
import org.opsli.modulars.business.iot.protocol.SyncChannelUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;

@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class CzTask {
        //3.添加定时任务
        @Scheduled(cron = "0 */1 * * * ?")
        private void configureTasks() {
            System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
            Channel channel= SyncChannelUtil.getChannel("002022047005z");
            if(channel!=null&&channel.isActive()){
                //发送校时请求
                byte[] bytes=new byte[4];
                bytes[0]=0x00;
                bytes[1]=0x08;
                bytes[2]=0x00;
                bytes[3]=0x34;
                String s= ConvertCode.bytesToHexString(bytes);
                System.out.println(s);
                String ss=ConvertCode.getCRC3(bytes);
                writeToClient(s+ss,channel,"读场站数据");
            }else{
                System.out.println("场站通道不活跃2");
            }


        }

    /**
     * 公用回写数据到客户端的方法
     * @param channel
     * @param mark 用于打印/log的输出
     * <br>//channel.writeAndFlush(msg);//不行
     * <br>//channel.writeAndFlush(receiveStr.getBytes());//不行
     * <br>在netty里，进出的都是ByteBuf，楼主应确定服务端是否有对应的编码器，将字符串转化为ByteBuf
     */
    private void writeToClient(final String receiveStr, Channel channel, final String mark) {
        try {
            ByteBuf bufff = Unpooled.buffer();//netty需要用ByteBuf传输
            bufff.writeBytes(ConvertCode.hexString2Bytes(receiveStr));//对接需要16进制
            channel.writeAndFlush(bufff).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    StringBuilder sb = new StringBuilder("");
                    if(!ZkUtils.isEmpty(mark)){
                        sb.append("【").append(mark).append("】");
                    }
                    if (future.isSuccess()) {
                        System.out.println("发送场站数据成功++++++");
                        System.out.println(sb.toString()+"回写成功"+receiveStr);
                    } else {
                        System.out.println(sb.toString()+"回写失败"+receiveStr);

                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("调用通用writeToClient()异常"+e.getMessage());

        }
    }

}
